package com.cloud.salon.common.base.util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Description 日期处理工具类
 * @Author wolf--LZH
 * @CreateDate 2019/5/19 0019 下午 9:02
 */
public class DateUtil {

    private final static int[] DOMAIN = {
            Calendar.YEAR,
            Calendar.MONTH,
            Calendar.DAY_OF_MONTH,
            Calendar.HOUR,
            Calendar.MINUTE,
            Calendar.SECOND
    };


    public final static int YEAR = 0;
    public final static int MONTH = 1;
    public final static int DAY = 2;
    public final static int HOUR = 3;
    public final static int MINUTE = 4;
    public final static int SECOND = 5;



    /*
     * @Description 通过日期格式和日期字符串获得 Date
     * @Author wolf--LZH
     */
    public static Date dateOfStr(String format, String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);

        Date date = null;
        try {
            date = sdf.parse(dateStr);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return date;
    }

    /*
     * @Description 将 Date 转化为特定格式的日期字符串
     * @Author wolf--LZH
     */
    public static String strOfDate(String format, Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);

        return sdf.format(date);
    }

    /*
     * @Description 对 Date 添加某时间单位
     * @Author wolf--LZH
     */
    public static Date addTime(Date date, int domain, int delta) {
        // 添加对应的时间单位
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(DOMAIN[domain], delta);


        return c.getTime();
    }

    /*
     * @Description 获取时间域内的时间字符串集合
     * @Author wolf--LZH
     */
    public static List<String> getDomainStr(Date startDate, Date endDate, int domain, String format) {
        List<Date> dates = getDomain(startDate, endDate, domain);

        List<String> dateStrList = new ArrayList<>();

        for (Date date: dates)
            dateStrList.add(strOfDate(format, date));

        return dateStrList;
    }

    /*
     * @Description 获取时间域内的时间集合
     * @Author wolf--LZH
     */
    public static List<Date> getDomain(Date startDate, Date endDate, int domain) {
        List<Date> dates = new ArrayList<>();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(endDate);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.MONTH, 1);
        endDate = calendar.getTime();

        Date current = new Date(startDate.getTime());

        while (endDate.after(current)) {
            dates.add(current);
            current = addTime(current, domain, 1);
        }

        return dates;
    }
}
